package com.liujit.common.exception;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.liujit.common.enums.BusinessExceptionEnum;
import com.liujit.common.enums.ResultCode;
import lombok.Data;
import org.springframework.lang.NonNull;

/**
 * @description: 业务异常
 * @author: liujun
 * @create: 2020/12/31 4:30 下午
 **/
@Data
public class BusinessException extends RuntimeException {

    private static final long serialVersionUID = -8688864736492422419L;

    /**
     * 异常枚举
     */
    protected ResultCode resultCode = ResultCode.FAILURE;

    /**
     * 返回code
     */
    protected Integer code = this.resultCode.code();

    /**
     * 返回msg
     */
    protected String msg = this.resultCode.msg();

    /**
     * 异常信息
     */
    protected Object errors;

    public BusinessException() {
        BusinessExceptionEnum exceptionEnum = BusinessExceptionEnum.getByEClass(this.getClass());
        if (exceptionEnum != null) {
            this.resultCode = exceptionEnum.getResultCode();
            this.code = this.resultCode.code();
            this.msg = this.resultCode.msg();
        }
    }

    public BusinessException(@NonNull String msg) {
        this.msg = msg;
    }

    public BusinessException(@NonNull ResultCode resultCode) {
        this.resultCode = resultCode;
        this.code = this.resultCode.code();
        this.msg = this.resultCode.msg();
    }

    public BusinessException(@NonNull ResultCode resultCode, @NonNull Object errors) {
        this(resultCode);
        this.errors = errors;
    }

    public BusinessException(@NonNull String format, Object... errors) {
        format = StrUtil.replace(format, "{}", "%s");
        this.msg = ArrayUtil.isEmpty(errors) ?
                String.format(format.replaceAll("%([^n])", "%%$1")) :
                String.format(format, errors);
    }
}
